/**
 * Parse string to Person object
 * String format:Person	Code;Name;Address;Email	Address(es);
 */
package data.converter.parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import data.converter.model.Address;
import data.converter.model.Person;

public class ParserToPerson {

//	private Person person;
	private HashMap<String,String> mapping = new HashMap<String, String>();
	private String[] names = {
			"personCode","names", "address", "emails"
	};
	private ParserToAddress mappingToAddress = new ParserToAddress();
	
	/**
	 * @param strValue Follow the "String format" strictly
	 * @return person
	 */
	public Person converterToPerson(String strValue) {
		String[] items = strValue.split(";");
		for(int i=0; i < items.length; i++) {
			mapping.put(names[i], items[i] == null ? "" : items[i]);
		}
		Person person = new Person();
		Address address = mappingToAddress.convertToAddress((mapping.get("address")));
		person.setAddress(address);
		person.setEmails(getEmails(mapping.get("emails")));
		person.setPersonCode(mapping.get("personCode"));
		String names = mapping.get("names");
		String[] nameItems = names.split(",");
		person.setFirstName(nameItems[0] != null ? nameItems[0] : "");
		person.setLastName(nameItems[1] != null ? nameItems[1] : "");
		return person;
	}
	
//	public Address convertToAddress(String strValue) {
//		Address address = new Address();
//		String[] items = strValue.split(",");
//		address.setStreet(items[0] != null ? items[0] : "");
//		address.setCity(items[1] != null ? items[1] : "");
//		address.setState(items[2] != null ? items[2] : "");
//		address.setZip(items[3] != null ? items[3] : "");
//		address.setCountry(items[4] != null ? items[4] : "");
//		return address;
//	}
	
	public List<String> getEmails(String strValue) {
		List<String> emails = new ArrayList<String>();
		if(strValue == null || strValue.isEmpty()) {
			return emails;
		}
		String[] items = strValue.split(",");
		for(String item: items) {
			Pattern pattern = Pattern.compile("[-a-zA-Z0-9]+@[a-z0-9]+.[a-z]+");
			Matcher matcher = pattern.matcher(item);
			if(matcher.matches()) {
				emails.add(item);
			}
		}
		return emails;
	}
}
